define([
    'angular',
    'config'
], function(angular, config) {
    var provider = angular.module('app.provider', []);

    provider.provider('KaptchaProvider', function() {
        this.$get = function() {
            return {
                load: function() {
                    return config.baseUrl + '/kaptcha.jpg';
                },
                refresh: function() {
                    return config.baseUrl + '/kaptcha.jpg?rid' + Math.random();
                }
            };
        };
    });

    provider.provider('ActionProvider', ['$provide', function($provide) {
        this.$get = function() {
            return {
                register: function(action) {
                    function Service($q, $http) {
                        this.$q = $q;
                        this.$http = $http;
                    }
                    Service.$inject = ['$q', '$http'];

                    angular.forEach(action.methods, function(methodUrl, methodName) {
                        Service.prototype[methodName] = function(args, options) {
                            var defer = this.$q.defer();
                            this.$http.post(config.baseUrl + action.baseUrl + methodUrl, args, options)
                            .then(function(response) {
                                defer.resolve(response.data);
                            }, function(response) {
                                defer.reject(response);
                            });

                            return defer.promise;
                        };
                    });

                    $provide.service(action.service, Service);
                }
            };
        };
    }]);

    return provider;
});
